package com.ganlucode.sipmock.sip.request.impl;

import com.ganlucode.sipmock.gb28181.constants.CmdType;
import com.ganlucode.sipmock.gb28181.constants.XmlNode;
import com.ganlucode.sipmock.sip.request.ISipRequestProcessor;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.sip.RequestEvent;
import javax.sip.message.Request;
import java.io.ByteArrayInputStream;


/**
 * @author GanLu
 */
@Slf4j
@Service("messageRequestProcessor")
public class MessageRequestProcessor implements ISipRequestProcessor {



    @Autowired
    @Qualifier("alarmProcessor")
    private ISipRequestProcessor alarmProcessor;

    @Autowired
    @Qualifier("catalogProcessor")
    private ISipRequestProcessor catalogProcessor;

    @Autowired
    @Qualifier("deviceProcessor")
    private ISipRequestProcessor deviceProcessor;

    @Autowired
    @Qualifier("keepAliveProcessor")
    private ISipRequestProcessor keepAliveProcessor;

    @Autowired
    @Qualifier("recordProcessor")
    private ISipRequestProcessor recordProcessor;

    /**
     * 处理MESSAGE请求
     *
     * @param evt
     */
    @Override
    public void process(RequestEvent evt) throws Exception {

        Request request = evt.getRequest();
        SAXReader reader = new SAXReader();
        Document xml = reader.read(new ByteArrayInputStream(request.getRawContent()));
        Element rootElement = xml.getRootElement();
        String cmd = rootElement.element(XmlNode.CMD_TYPE).getStringValue();

        switch (cmd) {

            case CmdType.MESSAGE_KEEP_ALIVE:
                log.info("接收到KeepAlive消息");
                keepAliveProcessor.process(evt);
                break;
            case CmdType.MESSAGE_CATALOG:
                log.info("接收到Catalog消息");
                catalogProcessor.process(evt);
                break;
            case CmdType.MESSAGE_DEVICE_INFO:
                log.info("接收到DeviceInfo消息");
                deviceProcessor.process(evt);
                break;
            case CmdType.MESSAGE_ALARM:
                log.info("接收到Alarm消息");
                alarmProcessor.process(evt);
                break;
            case CmdType.MESSAGE_RECORD_INFO:
                log.info("接收到RecordInfo消息");
                recordProcessor.process(evt);
                break;
            default:
                log.warn("没有对应处理类，cmd_type:{}",cmd);
                break;
        }

    }

}
